package operation.android.util;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Android代码修改页面
 *
 * AndroidViewModelFactory.java
 * VerificationViewModel.java
 * AndroidManifest.xml
 * EntityConstant.java
 */
public class AndroidAutoUpdate {
    static final OutFilePath outFilePath = new OutFilePath();
    // 测试文件路径
    static String testUrl = outFilePath.testUrl;
    // AppViewModelFactory
    final String appViewModelFactoryUrl = outFilePath.getAndroidOutPath() + outFilePath.appViewModelFactoryUrl;
    // VerificationViewModel
    final String verificationViewModelUrl = outFilePath.getAndroidOutPath() + outFilePath.verificationViewModelUrl;
    // AndroidManifest
    final String androidManifestUrl = outFilePath.getAndroidOutPath() + outFilePath.androidManifestUrl;
    // EntityConstant
    final String entityConstantUrl = outFilePath.getAndroidOutPath() + outFilePath.entityConstantUrl;

    /**
     * AppViewModelFactory.java  添加ViewModel工厂代码
     */
    public String AndroidViewModelFactory(Map<String, Object> valueMap) {
        String ClassName = valueMap.get("ClassName").toString();
        String projectName = valueMap.get("projectName").toString();

        String stopStr = "throw new IllegalArgumentException(\"Unknown ViewModel class: \" + modelClass.getName());";
        String importStr = "public class AppViewModelFactory extends ViewModelProvider.NewInstanceFactory {";
        Map<Integer, String> map = new HashMap<>();
        map.put(0, "        else if (modelClass.isAssignableFrom(" + ClassName + "ViewModel.class)) { // " + projectName);
        map.put(1, "            return (T) new " + ClassName + "ViewModel(mApplication, mRepository);");
        map.put(2, "        }");

        Map<Integer, String> importMap = new HashMap<>();
        importMap.put(0, "import cn.eoneplus.mes.ui.module.verification." + valueMap.get("classname") + "." + valueMap.get("ClassName") + "ViewModel;");
        updateUtil(appViewModelFactoryUrl, stopStr, importStr, map, importMap, 1);
        String res = "UPDATE 修改【AndroidViewModelFactory.java】成功";
        return res;
    }

    /**
     * VerificationViewModel.java  菜单添加代码
     *
     * @param valueMap
     */
    public String VerificationViewModel(Map<String, Object> valueMap) {
        String quanxian = "MENU_AUTHORIZATION_VERIFICATION_" + valueMap.get("class_name").toString().toUpperCase();
        String ClassName = valueMap.get("ClassName").toString();
        String projectName = valueMap.get("projectName").toString();
        String class_name = valueMap.get("class_name").toString();

        String stopStr = "observableList.setValue(itemViewModelList);";
        String importStr = " * ViewModel - 防错料";
        Map<Integer, String> map = new HashMap<>();
        map.put(0, "        if (authorizations.contains(EntityConstant." + quanxian + ")) {");
        map.put(1, "            itemViewModelList.add(new VerificationItemViewModel(this,");
        map.put(2, "                    VerificationMenuType.COMMON,");
        map.put(3, "                    " + ClassName + "Activity.class,");
        map.put(4, "                    R.string.verification_menu_" + class_name + ",");
        map.put(5, "                    ContextCompat.getDrawable(getApplication(), R.mipmap.verification_menu_call_material)));");
        map.put(6, "        }");

        Map<Integer, String> importMap = new HashMap<>();
        importMap.put(0, "import cn.eoneplus.mes.ui.module.verification." + valueMap.get("classname") + "." + valueMap.get("ClassName") + "Activity;");
        updateUtil(verificationViewModelUrl, stopStr, importStr, map, importMap, 2);
        String res = "UPDATE 修改【VerificationViewModel.java】成功";
        return res;
    }

    /**
     * AndroidManifest.xml  注册页面代码
     */
    public String AndroidManifest(Map<String, Object> valueMap) {
        String ClassName = valueMap.get("ClassName").toString();
        String classname = valueMap.get("classname").toString();
        String stopStr = "<!-- 我的 -->";
        Map<Integer, String> map = new HashMap<>();
        map.put(0, "        <!-- " + valueMap.get("projectName") + " -->");
        map.put(1, "        <activity");
        map.put(2, "            android:name=\".ui.module.verification." + classname + "." + ClassName + "Activity\" ");
        map.put(3, "            android:windowSoftInputMode=\"adjustPan\" />");

        Map<Integer, String> importMap = new HashMap<>();

        updateUtil(androidManifestUrl, stopStr, "", map, importMap, 10086);
        String res = "UPDATE 修改【AndroidManifest.xml】成功";
        return res;
    }

    /**
     * EntityConstant.java  菜单授权代码
     * @param valueMap
     */
    public String EntityConstant(Map<String, Object> valueMap) {
        String CLASSNAME = valueMap.get("class_name").toString().toUpperCase();
        String str = valueMap.get("class_name").toString().replace("_", "-");
        String stopStr = "// 菜单授权 - 我 - 同步数据";
        Map<Integer, String> map = new HashMap<>();
        map.put(0, "    // 菜单授权 - 防错料 - " + valueMap.get("projectName"));
        map.put(1, "    public static final String MENU_AUTHORIZATION_VERIFICATION_" + CLASSNAME + " = \"mb:verification:" + str + "\";");
        Map<Integer, String> importMap = new HashMap<>();

        updateUtil(entityConstantUrl, stopStr, "", map, importMap, 10086);
        String res = "UPDATE 修改【EntityConstant.java】成功";
        return res;
    }


//    public static void main(String args[]) {
//        // 测试一
//        Map<String, Object> valueMap = new HashMap<>();
//        valueMap.put("ClassName", "HelloHermit");
//        valueMap.put("projectName", "测试杨凡");
//        valueMap.put("class_name", "hello_hermit");
//        valueMap.put("classname", "hellohermit");
//        AndroidViewModelFactoryTest(valueMap);
//
//
//    }


    /**
     * 修改代码通用工具方法 java文件
     *
     * @param url       需要修改的文件地址
     * @param stopStr   截取的代码结束标识
     * @param importStr 引入代码的结束标识
     * @param addMap    需要添加的代码片段
     * @param importMap 需要引入的代码片段
     * @param importNum 引入标识距离开始插入代码的行数 如果不需要插入import代码,推荐传参10086
     */
    public static void updateUtil(String url, String stopStr, String importStr, Map<Integer, String> addMap, Map<Integer, String> importMap, int importNum) {
        // 读取文件
        Map<Integer, String> getMap = new HashMap<>();
        BufferedReader br = null;
        String file = "";
        try {
            br = new BufferedReader(new FileReader(url));    // 读取文件
            String line = null;
            while ((line = br.readLine()) != null) {// 按行读取
                if (line.equals("}") || line.contains("</manifest>")) {
                    file += line + "#";
                    break;
                } else {
                    file += line + "#";
                }
            }
            String[] split = file.split("#");
            int flag = 0;
            if (importNum < 100) {
                for (int line2 = 0; line2 < split.length - 1; line2++) {
                    if (split[line2].contains(importStr)) {
                        flag = line2;
                    }
                }
            }
            int flagAdd = 0;
            // 插入代码
            for (int j = 0; j < split.length - 1; j++) {
                if (split[j].contains(stopStr)) {
                    flagAdd = j;
                }
            }
            if (importNum < 100) {
                // 插入引用类
                for (int line1 = 0; line1 < split.length - 1 + importMap.size() + addMap.size(); line1++) {
                    // 在import之前 不包含 放入之前数据
                    if (line1 < flag - importNum) {
                        getMap.put(line1, split[line1]);
                        // import前一个 包含  flag - 1 为开始写入的行
                    } else if (line1 >= flag - importNum && line1 < flag - importNum + importMap.size()) {
                        getMap.put(line1, importMap.get(line1 - flag + importNum));
                        // 写完行的下一行
                    } else if (line1 == flag - importNum + importMap.size()) {
                        getMap.put(line1, "");
                        // 大于写完行的下一行 小于
                    } else if (line1 > flag - importNum + importMap.size() && line1 < flagAdd + importMap.size()) {
                        getMap.put(line1, split[line1 - importMap.size()]);
                    } else if (line1 >= flagAdd + importMap.size() && line1 < flagAdd + addMap.size() + importMap.size()) {
                        getMap.put(line1, addMap.get(line1 - importMap.size() - flagAdd));
                    } else if (line1 >= flagAdd + addMap.size() + importMap.size()) {
                        getMap.put(line1, split[line1 - addMap.size() - importMap.size()]);
                    }
                }
            } else {
                for (int line1 = 0; line1 < split.length + addMap.size(); line1++) {
                    // 预留一行
//                    if (line1 < flagAdd - 1) {
//                        getMap.put(line1, split[line1]);
//                    } else if (line1 >= flagAdd - 1 && line1 < flagAdd - 1 + addMap.size()) {
//                        getMap.put(line1, addMap.get(line1 - flagAdd + 1));
//                    } else if (line1 >= flagAdd - 1 + addMap.size()) {
//                        getMap.put(line1, split[line1 - addMap.size()]);
//                    }
                    // 不预留
                    if (line1 < flagAdd) {
                        getMap.put(line1, split[line1]);
                    } else if (line1 >= flagAdd && line1 < flagAdd + addMap.size()) {
                        getMap.put(line1, addMap.get(line1 - flagAdd));
                    } else if (line1 >= flagAdd + addMap.size()) {
                        getMap.put(line1, split[line1 - addMap.size()]);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 修改文件
        File outfile = new File(url);
        String info = "";
        // 输入文件
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(outfile);
            for (int i = 0; i < getMap.size(); i++) {
                info = System.getProperty("line.separator") + getMap.get(i);
                fileWriter.write(info);
            }
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试
     */
    public static void AndroidViewModelFactoryTest(Map<String, Object> valueMap) {
        // 测试AppViewModelFactory
//        Map<String, Object> valueMap = new HashMap<>();
//        valueMap.put("ClassName", "HelloHermit");
//        valueMap.put("projectName", "测试杨凡");
//        valueMap.put("classname", "hellohermit");
//        // TODO 以上map需要入参
//        String stopStr = "throw new IllegalArgumentException(\"Unknown ViewModel class: \" + modelClass.getName());";
//        String importStr = "public class AppViewModelFactory extends ViewModelProvider.NewInstanceFactory {";
//        Map<Integer, String> map = new HashMap<>();
//        map.put(0, "        }else if (modelClass.isAssignableFrom(" + valueMap.get("ClassName") + "ViewModel.class)) { // " + valueMap.get("projectName"));
//        map.put(1, "            return (T) new " + valueMap.get("ClassName") + "ViewModel(mApplication, mRepository);");
//        map.put(2, "        }");
////        map.put(3, "        throw new IllegalArgumentException(\"Unknown ViewModel class: \" + modelClass.getName());");
////        map.put(4, "    }");
////        map.put(5, "}");
//
//        Map<Integer, String> importMap = new HashMap<>();
//        importMap.put(0, "import cn.eoneplus.mes.ui.module.verification." + valueMap.get("classname") + "." + valueMap.get("ClassName") + "ViewModel;");
//        updateUtil(testUrl, stopStr, importStr, map, importMap, 1);

        // 测试VerifivationViewModel
//        String quanxian = "MENU_AUTHORIZATION_VERIFICATION_" + valueMap.get("class_name").toString().toUpperCase();
//        String ClassName = valueMap.get("ClassName").toString();
//        String projectName = valueMap.get("projectName").toString();
//        String class_name = valueMap.get("class_name").toString();
//
//        String stopStr = "observableList.setValue(itemViewModelList);";
//        String importStr = " * ViewModel - 防错料";
//        Map<Integer, String> map = new HashMap<>();
//        map.put(0, "        if (authorizations.contains(EntityConstant." + quanxian + ")) {");
//        map.put(1, "            itemViewModelList.add(new VerificationItemViewModel(this,");
//        map.put(2, "                    VerificationMenuType.COMMON,");
//        map.put(3, "                    " + ClassName +"Activity.class,");
//        map.put(4, "                    R.string.verification_menu_" + class_name + ",");
//        map.put(5, "                    ContextCompat.getDrawable(getApplication(), R.mipmap.verification_menu_" + class_name + ")));");
//        map.put(6, "        }");
//
//        Map<Integer, String> importMap = new HashMap<>();
//        importMap.put(0, "import cn.eoneplus.mes.ui.module.verification." + valueMap.get("classname") + "." + valueMap.get("ClassName") + "Activity;");
//        updateUtil(testUrl, stopStr, importStr, map, importMap, 2);

        // 测试AndroidManifest.xml
//        String ClassName = valueMap.get("ClassName").toString();
//        String classname = valueMap.get("classname").toString();
//        String stopStr = "<!-- 我的 -->";
//        Map<Integer, String> map = new HashMap<>();
//        map.put(0, "        <!-- " + valueMap.get("projectName") + " -->");
//        map.put(1, "        <activity");
//        map.put(2, "            android:name=\".ui.module.verification." + classname + "." + ClassName + "Activity\" ");
//        map.put(3, "            android:windowSoftInputMode=\"adjustPan\" />");
//
//        Map<Integer, String> importMap = new HashMap<>();
//
//        updateUtil(testUrl, stopStr, "", map, importMap, 10086);

        // 测试EntityConstant
        String CLASSNAME = valueMap.get("class_name").toString().toUpperCase();
        String str = valueMap.get("class_name").toString().replace("_", "-");
        String stopStr = "// 菜单授权 - 我 - 同步数据";
        Map<Integer, String> map = new HashMap<>();
        map.put(0, "    // 菜单授权 - 防错料 - " + valueMap.get("projectName"));
        map.put(1, "    public static final String MENU_AUTHORIZATION_VERIFICATION_" + CLASSNAME + " = \"mb:verification:" + str + "\";");
        Map<Integer, String> importMap = new HashMap<>();

        updateUtil(testUrl, stopStr, "", map, importMap, 10086);
    }
}
